package edu.whut.mall.user.controller;

import edu.whut.mall.common.constant.WxPayConstant;
import edu.whut.mall.common.util.CommonUtil;
import edu.whut.mall.common.util.WeixinPayUtils;
import edu.whut.mall.common.util.XmlUtils;
import edu.whut.mall.common.api.ResponseMap;
import edu.whut.mall.common.enums.WxTradeType;
import edu.whut.mall.user.service.IPayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.util.Map;

/**
 * 使用嫦娥创新商户账号
 */


@Api(tags = {"微信支付(小程序)"}, description = "微信支付接口", produces = MediaType.APPLICATION_JSON_VALUE)
@RestController
@RequestMapping(value = "/wxpay")
@Slf4j
public class PayController {

    @Autowired
    private IPayService payService;


    @ApiOperation(value = "微信支付", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openid", value = "openid", paramType = "form", dataType = "String"),
            @ApiImplicitParam(name = "tradeId", value = "订单id", paramType = "form", dataType = "int"),
            @ApiImplicitParam(name = "type", value = "0为普通交易，1为优品体验", paramType = "form", dataType = "int")
    })
    @RequestMapping(value = "/prepay", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public Map prePay(HttpServletRequest request, Integer userId, String openid, int tradeId, int type) throws Exception {
        log.info("传入的userId:" + userId);
        log.info("传入的openId:" + openid);
        log.info("传入的tradeId:" + tradeId);
        log.info("传入的type:" + type);
        ResponseMap jmap = ResponseMap.getInstance();
        String content = payService.prePay(request, userId, openid, tradeId, type, WxTradeType.JSAPI);
        return jmap.putValue(content);
    }



    @ApiOperation(value = "微信买东西支付结果通知", httpMethod = "POST")
    @RequestMapping("/wxnotifytrade")
    public void wxnotifytrade(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> result = getWxPayNotifyMap(request, response);
        if (result != null){
            String out_trade_no=(String) result.get("out_trade_no");
            log.info("支付成功:"+out_trade_no);
            Integer flag = payService.confirmPayStatus(out_trade_no);
            if (flag > 0) {
                log.info("tradeId: " + flag);
            }
        }
    }


    private Map<String, Object> getWxPayNotifyMap(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String result = WeixinPayUtils.readFromInputStream(request.getInputStream());
        Map<String, Object> xmlBodyContext = XmlUtils.getXmlBodyContext(result);

        for (Map.Entry<String, Object> entry : xmlBodyContext.entrySet()) {
            log.info("属性: " + entry.getKey() + ", 值: " + entry.getValue());
        }

        if (!WeixinPayUtils.isSignatureValid(result, WxPayConstant.CHANGE_KEY)) {    //签名不成功
            log.info("交易微信支付签名验证错误!");
            return null;
        } else {
            log.info("交易微信支付签名验证正确!");
            //返给微信成功信息
            String responseInfo = WxPayConstant.resSuccessXml;
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            out.write(responseInfo.getBytes());
            out.flush();
            out.close();
            //检查支付的表
            return xmlBodyContext;
        }
    }


    @ApiOperation(value = "订单付款查询", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "outTradeNo", value = "交易单单号", paramType = "form", dataType = "String"),
    })
    @RequestMapping(value = "/orderQuery", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public Map orderQuery(HttpServletRequest request, String outTradeNo) throws Exception {
        ResponseMap map = ResponseMap.getInstance();
        String desc = payService.orderQuery(outTradeNo);
        return map.putValue(desc);
    }


    @ApiOperation(value = "资金退还", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
    })
    @RequestMapping(value = "/refund", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public Map refund(HttpServletRequest request, String outTradeNo, int userId) throws Exception {
        ResponseMap map = ResponseMap.getInstance();

        String clientIP = CommonUtil.getClientIp(request);

        Integer flag= payService.refund(userId,outTradeNo,clientIP);

        if (flag==1){
            return map.putSuccess("退款成功");
        }else {
            return map.putFailure("资金退还失败","不存在该订单或者微信支付退回失败",-1);
        }
    }

}
